﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebSiteAPI.DbContexts;
using WebSiteAPI.Entities;

namespace WebSiteAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountsController : ControllerBase
    {
        private readonly CCDemoDbContext _context;

        public AccountsController(CCDemoDbContext context)
        {
            _context = context;
        }

        // GET: api/Accounts
        [HttpGet]
        public async Task<ActionResult<ListResult<IEnumerable<Account>>>> GetAccounts(int pageNo =1, int pageSize = 10)
        {
            var dataCount = await _context.Accounts.CountAsync();
            var data = await _context.Accounts.Skip((pageNo - 1)* pageSize).Take(pageSize).OrderBy(e=>e.Name).ToListAsync();
            var result = new ListResult<IEnumerable<Account>>()
            {
                pageSize = pageSize,
                pageNo = pageNo,
                totalCount = dataCount,
                totalPage = (int)Math.Ceiling(dataCount * 1M / pageSize),
                data = data
            };
            return result;
        }

        // GET: api/Accounts/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Account>> GetAccount(Guid id)
        {
            var account = await _context.Accounts.FindAsync(id);
            if (account == null)
            {
                return NotFound();
            }
            return account;
        }

        // POST: api/Accounts
        [HttpPost]
        public async Task<ActionResult<Account>> PostAccount(AccountDTO account)
        {
            Account accountData = new Account()
            {
                Name = account.Name,
                PhoneNumber = account.PhoneNumber,
                Notes = account.Notes,
                Source = "WebSite"
            };
            _context.Accounts.Add(accountData);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetAccount), new { id = accountData.Id }, accountData);
        }

        [HttpPatch("{id}")]
        public async Task<IActionResult> PutAccount(Guid id, Account account)
        {
            if (id != account.Id)
            {
                return BadRequest();
            }

            var accountData = await _context.Accounts.SingleAsync(x => x.Id == id);

            accountData.Name = account.Name;
            accountData.PhoneNumber = account.PhoneNumber;
            accountData.Notes = account.Notes;

            _context.Entry(accountData).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccountExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteAccount(Guid id)
        {
            var account = await _context.Accounts.FindAsync(id);
            if (account == null)
            {
                return NotFound();
            }

            _context.Accounts.Remove(account);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool AccountExists(Guid id)
        {
            return _context.Accounts.Any(e => e.Id == id);
        }
    }
}
